﻿/*
 * Сделано в SharpDevelop.
 * Пользователь: Eugenij
 * Дата: 30.01.2014
 * Время: 20:29
 * 
 * Для изменения этого шаблона используйте Сервис | Настройка | Кодирование | Правка стандартных заголовков.
 */
using System;
using System.Drawing;
using System.IO.Ports;
using System.Threading;
using System.Windows.Forms;
using System.Collections.Generic;

namespace hwspeed
{
    /// <summary>
    /// Description of Modem.
    /// </summary>
    class Modem
    {
        private SerialPort modem_port;
        private string port_name;
        
        public string ModemPort {
            get {
                return port_name;
            }
        }

        public Modem(string prtname)
        {
            port_name = null;
            modem_port = null;
            Setup(prtname);
        }
        
        
        public Modem()
        {
            port_name = null;
            modem_port = null;
        }
        
        ~Modem()
        {
            Reset();
        }
        
        
        public bool Setup(string prtname)
        {
            Reset();
            if (prtname == null)
            {
                return false;
            }
            modem_port = new SerialPort();
            modem_port.PortName = prtname;
            modem_port.BaudRate = 9600;
            modem_port.Parity = Parity.None;
            modem_port.DataBits = 8;
            modem_port.StopBits = StopBits.One;
            modem_port.Handshake = Handshake.None;
            modem_port.DtrEnable = false;
            modem_port.RtsEnable = false;
            modem_port.NewLine = "\r\n";
            modem_port.WriteTimeout = 300;
            modem_port.ReadTimeout = 300;
            
            if (Configuration.CommConfigConfigured){
                modem_port.BaudRate = (int)Configuration.CommConfig.dcbx.BaudRate;
                modem_port.DataBits = Configuration.CommConfig.dcbx.ByteSize;
                
                if (Configuration.CommConfig.dcbx.StopBits == 0)
                    modem_port.StopBits = StopBits.None;
                if (Configuration.CommConfig.dcbx.StopBits == 1)
                    modem_port.StopBits = StopBits.One;
                if (Configuration.CommConfig.dcbx.StopBits == 2)
                    modem_port.StopBits = StopBits.Two;
            }
            
            modem_port.Open();
            if (modem_port.IsOpen)
            {
                port_name = prtname;
                return true;
            }
            port_name = null;
            modem_port = null;
            return false;
        }
        
        
        public void Reset()
        {
            if (modem_port != null)
            {
                if (modem_port.IsOpen)
                {
                    modem_port.DiscardInBuffer();
                    modem_port.DiscardOutBuffer();
                    modem_port.Close();
                }
                modem_port = null;
            }
        }

        // return AT result code. "OK","ERROR",etc
        public static string atResult(string[] arr)
        {
            if (arr != null && arr.Length > 0)
            {
                return arr[arr.Length-1];
            }
            return null;
        }
        
        // return AT result without result code.
        public static string atBody(string[] arr)
        {
            if (arr != null)
            {
                if (arr.Length > 1)
                    return string.Join("\r\n", arr, 0, arr.Length-1);
                if (arr.Length == 1)
                    return arr[0] + "\r\n";
            }
            return null;
        }
        
        // check modem version
        public bool IsHuaweiE3131()
        {
            if (modem_port.IsOpen)
            {
                string[] rv = AtCmd("AT");
                if (atResult(rv) != "OK")
                {
                    return false;
                }
                rv = AtCmd("ATI");
                foreach (var sResult in rv)
                {
                    if (sResult == "Model: E3131")
                        return true;
                }
            }
            return false;
        }
        

        // send AT command to modem
        public string[] AtCmd(string at_cmd)
        {
            var sc = new List<string>();
            try {
                if (modem_port.IsOpen)
                {
                    modem_port.WriteLine(at_cmd);
                    Thread.Sleep(10);
                    string l = modem_port.ReadLine();
                    bool dataok = false;
                    do {
                        l = modem_port.ReadLine();
                        if (l.Trim() == "")
                        {
                            if (dataok)
                            {
                                break;
                            }
                            dataok = true;
                        }
                        sc.Add(l);
                    } while (l != null);
                }
            } catch (TimeoutException) {
                
            }
            return sc.ToArray();
        }
        
    }
}
